<?php
/*
 * @Description    : 支付宝支付异步通知接口
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2021-04-05 17:13:54
 * @LastEditors    : QianLong
 * @LastEditTime   : 2022-05-28 17:16:28
 */

namespace app\notify\controller;

use Alipay\EasySDK\Kernel\Factory;
use app\common\RedisCache;
use app\common\service\alipay\Options;
use app\lib\exception\ApiException;
use Ecmpay\Ecmpay\Ecmpay;

class Alipay extends \app\BaseController
{
    protected $redisCache;
    protected $platformSetting;
    public function initialize()
    {
        $this->redisCache = new RedisCache();
        $this->platformSetting = $this->redisCache::getSysPaymentSetting();
        if (!isset($this->platformSetting['pay_platform']) || $this->platformSetting['pay_platform'] != 'ecmpay') {
            Factory::setOptions((new Options)->getOptions());
        } else {
            $ecmpaySetting = $this->redisCache::getSysPaySetting('alipay');
            Ecmpay::init(['app_id' => $ecmpaySetting['app_id'], 'auth_app_id' => $ecmpaySetting['auth_app_id'], 'appSecret' => $ecmpaySetting['app_secret']]);
        }
    }
    public function url()
    {
        if (request()->isPost()) {
            $postData = input('param.');
            if (!empty($postData)) {
                if (!isset($this->platformSetting['pay_platform']) || $this->platformSetting['pay_platform'] != 'ecmpay') {
                    $result = Factory::payment()->Common()->verifyNotify($postData);
                    //支付成功，完成你的逻辑
                    //例如连接数据库，获取付款金额$result['total_amount']，获取订单号$result['out_trade_no']修改数据库中的订单状态等;
                    //交易金额，单位为元：$result['total_amount']
                    //商户订单号：$result['out_trade_no']
                    //支付宝交易号：$result['trade_no']
                    //交易状态：$postData['trade_status']：TRADE_FINISHED（交易完结）、TRADE_SUCCESS（支付成功）
                    //具体详细请看支付宝文档：https://opendocs.alipay.com/apis/api_1/alipay.trade.page.pay#%E5%93%8D%E5%BA%94%E5%8F%82%E6%95%B0
                    var_dump($result);
                } else {
                    if (!Ecmpay::signVerify($postData)) {
                        throw new ApiException('喵付通支付签名校验失败');
                    }
                    if ($postData['event'] == 'PAYMENT_SUCCESS') {
                        //具体参数详细请看文档：http://doc.21ds.cn/index?project_id=4683630058798691&doc_id=4687155804231000
                    }
                }
                echo 'success';
            } else {
                echo "empty";
            }
        }
    }
}
